<template>
    <view class="main">
        <view class="dateList">
            <scroll-view 
            class="scroll-view" 
            scroll-x 
            :show-scrollbar="false"
            :scroll-left="scrollLeft"
            scroll-with-animation
            @scroll="handleScroll"
            ref="scrollView"
            >
            <view class="scroll-container">
                <view 
                class="scroll_item"
                v-for="(item, index) in formattedDateList" 
                :key="index"
                :id="'item-' + index"
                :class="{
                    'active': activeIndex === index,
                    'first-item': index === 0,
                    'last-item': index === formattedDateList.length - 1,
                    'middle-item': index > 0 && index < formattedDateList.length - 1
                }"
                @click="handleItemClick(item,index)"
                >
                <view class="content">
                        <view class="text">{{ item.day }}</view>
                        <view class="text">{{ item.formattedDate }}</view>
                        <view class="text">￥{{ item.adult }}</view>
                </view>
                </view>
            </view>
            </scroll-view>
        </view>
       <view class="calendar">
            <wd-calendar v-model="value" @confirm="handleConfirm">
                <view class="btn">更多日期<wd-icon name="arrow-right" size="22rpx"></wd-icon></view>
            </wd-calendar>
       </view>
         
    </view>
</template>

<script setup>
import { ref, onMounted, nextTick ,getCurrentInstance ,defineProps, defineEmits,watch} from 'vue';
const emit = defineEmits(['getDateObj']);
const props = defineProps({
    dateList: {
        type: Array,
        required: true
      }
  });

// const dateList = ref([
//       {adult:'889',children:'598',thaliDate:'2025-05-03'},
//       {adult:'889',children:'598',thaliDate:'2025-05-04'},
//       {adult:'889',children:'598',thaliDate:'2025-05-05'},
//       {adult:'889',children:'598',thaliDate:'2025-05-06'},
//       {adult:'889',children:'598',thaliDate:'2025-05-07'},
//       {adult:'889',children:'598',thaliDate:'2025-05-08'},
//       {adult:'889',children:'598',thaliDate:'2025-05-09'},
//       {adult:'889',children:'598',thaliDate:'2025-05-10'},
//       {adult:'889',children:'598',thaliDate:'2025-05-11'},
//       {adult:'889',children:'598',thaliDate:'2025-05-12'},
//   ]);

const activeIndex = ref(0);
const scrollLeft = ref(0);
const currentScrollLeft = ref(0);
const scrollView = ref(null);
const instance = getCurrentInstance().proxy;

const scrollToPosition = (index) => {
  const query = uni.createSelectorQuery().in(instance);
  query
    .select('.scroll-view')
    .boundingClientRect() // 获取scroll-view的位置信息
    .select(`#item-${index}`)
    .boundingClientRect() // 获取目标item的位置信息
    .exec((res) => {
      if (!res || res.length < 2 || !res[0] || !res[1]) return;
      const scrollRect = res[0];
      const itemRect = res[1];

      // 计算item相对于scroll-view的位置
      const itemPosition = itemRect.left - scrollRect.left + currentScrollLeft.value;

      let targetScrollLeft;
      const scrollViewCenter = scrollRect.width / 2;
      const itemCenter = itemRect.width / 2;

      if (index === 0) {
        targetScrollLeft = 0;
      } else if (index === props.dateList.length - 1) {
        const totalContentWidth = (props.dateList.length - 1) * 28;
        const allItemsWidth = props.dateList.length * itemRect.width;
        targetScrollLeft = allItemsWidth + uni.upx2px(totalContentWidth) - scrollRect.width;
      } else {
        targetScrollLeft = itemPosition - scrollViewCenter + itemCenter;
      }

      // 边界检查
      const maxScrollLeft = (props.dateList.length * itemRect.width +
        (props.dateList.length - 1) * uni.upx2px(30)) - scrollRect.width;
      const finalScrollLeft = Math.max(0, Math.min(targetScrollLeft, maxScrollLeft));

      // 强制更新滚动位置
      scrollLeft.value = finalScrollLeft;
    });
};
const formattedDateList = ref([]);
// 处理日期函数
const handleDateList = () => {
    const today = new Date();
    formattedDateList.value = props.dateList.map(item => {
        const date = new Date(item.thaliDate); // 解析原始thaliDate
        const daysDiff = Math.floor((date - today) / (1000 * 60 * 60 * 24) + 1);
        
        // 计算显示文本
        let dayText;
        if (daysDiff === 0) {
            dayText = '今天';
        } else if (daysDiff === 1) {
            dayText = '明天';
        } else if (daysDiff === 2) {
            dayText = '后天';
        } else {
            dayText = getWeekday(date);
        }
        
        // 返回新对象，保留原始thaliDate，新增formattedDate和day
        return {
            ...item,
            day: dayText,
            formattedDate: formatDate(date) // 格式化为“x月x日”
        };
    });
};

// 监听props.dateList变化，重新处理数据
watch(() => props.dateList, () => {
    if(props.dateList && props.dateList.length > 0) {
        handleDateList();
        handleItemClick(formattedDateList.value[0], 0); // 默认选中第一条数据
    }
},{deep:true,immediate:true});

// 初始化处理
onMounted(() => {
    // handleDateList();
    // handleItemClick(formattedDateList.value[0], 0); // 默认选中第一条数据
});

// 工具函数
const formatDate = (date) => {
    return `${date.getMonth() + 1}月${date.getDate()}日`;
};

const getWeekday = (date) => {
    const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    return weekdays[date.getDay()];
};

const handleItemClick = async(e,index) => {
  activeIndex.value = index;
  await nextTick();
  scrollToPosition(index);
  emit('getDateObj', e);
};

const handleScroll = (e) => {
    currentScrollLeft.value = e.detail.scrollLeft;
};
const value = ref(Date.now())
const handleConfirm = ({ value })=> {
  console.log(value)
}
</script>

<style lang="scss" scoped>
.main{
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 48rpx;
    .dateList{
        flex: 1;
        width: calc(100% - 80rpx);
        .scroll-view {
            white-space: nowrap;
            width: 100%;
        }
        
        .scroll-container {
            display: inline-flex;
            padding: 0 0;
        }
        .scroll_item {
            display: inline-flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 166rpx;
            width: 145rpx;
            background-color: #eeefe7;
            border-radius: 10rpx;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
            flex-shrink: 0;
            .content{
                text-align: center;
                .text{
                    font-size: 25rpx;
                }
            }
        }
        .scroll_item.first-item {
            margin-left: 0;
            margin-right: 6rpx;
        }
        
        .scroll_item.last-item {
            margin-right: 0;
            margin-left: 6rpx;
        }
        
        .scroll_item.middle-item {
            margin: 0 6rpx;
        }
        
        .scroll_item.active {
            background: #1b9c61;
            color: #fff;
        }
    }
    .calendar{
        margin-left: 10rpx;
        .btn{
            display: flex;
            background: none;
            align-items: center;
            justify-content: center;
            border: none;
            font-size: 25rpx;
            width: 80rpx;
        }
    }
}
</style>